<template>
  <div class="settings-management">
    <div class="header-with-back">
      <button class="back-btn" @click="$emit('back')">
        <el-icon><ArrowLeft /></el-icon> 返回
      </button>
      <h1 class="page-title">系统设置</h1>
    </div>
    
    <LoadingSpinner v-if="isLoading" message="加载系统设置..." />
    
    <div v-else class="settings-content">
      <div v-if="settings.length === 0" class="no-settings">
        暂无系统设置数据
      </div>
      
      <div v-else class="settings-list">
        <div class="settings-header">
          <h2>系统设置列表</h2>
          <button class="btn btn-primary" @click="saveSettings">保存设置</button>
        </div>
        
        <table>
          <thead>
            <tr>
              <th>设置名称</th>
              <th>设置值</th>
              <th>描述</th>
              <th>更新时间</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="setting in settings" :key="setting.id">
              <td>{{ setting.setting_key }}</td>
              <td>
                <div class="toggle-switch">
                  <input
                    type="checkbox"
                    :id="`setting-${setting.id}`"
                    v-model="setting.valueBoolean"
                    @change="updateSettingValue(setting)"
                  />
                  <label :for="`setting-${setting.id}`"></label>
                </div>
              </td>
              <td>
                <input 
                  type="text" 
                  v-model="setting.description" 
                  class="description-input"
                  @change="markSettingChanged(setting)"
                />
              </td>
              <td>{{ formatDate(setting.updated_at) }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    
    <!-- Toast通知组件 -->
    <Toast 
      :message="toastMessage" 
      :type="toastType" 
      :visible="showToast" 
      @close="showToast = false" 
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from '@/api/apiClient'
import Toast from '@/components/Toast.vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'
import { ArrowLeft } from '@element-plus/icons-vue'

// 定义事件
defineEmits(['back'])

// 状态变量
const settings = ref([])
const originalSettings = ref([])
const isLoading = ref(true)
const showToast = ref(false)
const toastMessage = ref('')
const toastType = ref('info')

// 显示通知
const showNotification = (message, type = 'info') => {
  toastMessage.value = message
  toastType.value = type
  showToast.value = true
}

// 获取系统设置
const fetchSettings = async () => {
  isLoading.value = true
  try {
    console.log('开始获取系统设置...')
    const response = await api.admin.getSettings()
    console.log('获取系统设置API响应:', response)
    
    // 转换value为布尔值便于UI显示
    settings.value = response.map(setting => ({
      ...setting,
      valueBoolean: setting.value === '1' || setting.value === 1 || setting.value === true
    }))
    
    // 保存原始设置用于比较
    originalSettings.value = JSON.parse(JSON.stringify(settings.value))
    console.log('获取的系统设置:', settings.value)
  } catch (error) {
    console.error('获取系统设置失败:', error)
    showNotification('获取系统设置失败', 'error')
  } finally {
    isLoading.value = false
  }
}

// 更新设置值
const updateSettingValue = (setting) => {
  // 更新value字段，以便发送到服务器
  setting.value = setting.valueBoolean ? '1' : '0'
  console.log(`设置 ${setting.setting_key} 已更改为: ${setting.value}`)
}

// 标记设置描述被修改
const markSettingChanged = (setting) => {
  console.log(`设置 ${setting.setting_key} 描述已修改为: ${setting.description}`)
  // 不需要额外操作，因为修改会直接更新模型
}

// 保存所有更改的设置
const saveSettings = async () => {
  try {
    // 找出所有被修改的设置
    const changedSettings = settings.value.filter(setting => {
      const original = originalSettings.value.find(o => o.id === setting.id)
      if (!original) return false
      
      // 检查值或描述是否有变化
      const valueChanged = original.value !== setting.value
      const descriptionChanged = original.description !== setting.description
      
      return valueChanged || descriptionChanged
    })
    
    if (changedSettings.length === 0) {
      showNotification('没有设置被修改', 'info')
      return
    }
    
    // 准备要发送的设置数据，只包含id、value和description
    const settingsToUpdate = changedSettings.map(setting => ({
      id: setting.id,
      value: setting.valueBoolean ? 1 : 0,
      description: setting.description
    }))
    
    console.log('要更新的设置:', settingsToUpdate)
    
    // 发送更新请求
    console.log('开始调用更新设置API...')
    const result = await api.admin.updateSettings(settingsToUpdate)
    console.log('更新设置API响应:', result)
    
    // 更新原始设置
    originalSettings.value = JSON.parse(JSON.stringify(settings.value))
    
    showNotification('系统设置已成功更新', 'success')
    
    // 重新获取设置，确保数据同步
    await fetchSettings()
  } catch (error) {
    console.error('更新系统设置失败:', error)
    showNotification('更新系统设置失败', 'error')
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 页面加载时获取设置
onMounted(() => {
  fetchSettings()
})
</script>

<style scoped>
.settings-management {
  width: 100%;
}

.header-with-back {
  display: flex;
  align-items: center;
  margin-bottom: 2rem;
}

.back-btn {
  display: flex;
  align-items: center;
  background: none;
  border: none;
  color: #3b82f6;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  padding: 0.5rem 0.75rem;
  margin-right: 1rem;
  border-radius: 4px;
}

.back-btn:hover {
  background-color: #eff6ff;
}

.back-btn .el-icon {
  margin-right: 0.25rem;
}

.page-title {
  margin-bottom: 0;
  font-size: 1.8rem;
  color: #374151;
}

.settings-content {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  padding: 1.5rem;
}

.no-settings {
  text-align: center;
  padding: 3rem 0;
  color: #6b7280;
  font-size: 1.1rem;
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.settings-header h2 {
  margin: 0;
  font-size: 1.25rem;
  color: #374151;
}

.btn {
  padding: 0.5rem 1rem;
  border-radius: 4px;
  border: none;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
}

.btn-primary {
  background-color: #3b82f6;
  color: white;
}

.btn-primary:hover {
  background-color: #2563eb;
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 1rem;
}

th {
  text-align: left;
  padding: 1rem;
  background-color: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
  font-weight: 500;
  color: #374151;
}

td {
  padding: 1rem;
  border-bottom: 1px solid #e5e7eb;
  color: #4b5563;
}

/* 开关样式 */
.toggle-switch {
  position: relative;
  display: inline-block;
  width: 50px;
  height: 24px;
}

.toggle-switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.toggle-switch label {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 24px;
}

.toggle-switch label:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

.toggle-switch input:checked + label {
  background-color: #3b82f6;
}

.toggle-switch input:focus + label {
  box-shadow: 0 0 1px #3b82f6;
}

.toggle-switch input:checked + label:before {
  transform: translateX(26px);
}

/* 描述输入框样式 */
.description-input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  font-size: 0.875rem;
  color: #4b5563;
}

.description-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
}
</style> 